package everyday;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import entity.Contact;
import org.junit.jupiter.api.Test;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 生成vcf文件：用于导入手机通讯录
 *
 * @author gaojie
 * @date 2023-08-15
 */
public class VCFOperation {

    /**
     * 测试 java 代码用拼接字符串的方式生成 vcf
     */
    @Test
    void test01() {
        Contact[] contacts = {
                new Contact("张1", "18877771001", "18866661001@qq.com"),
                new Contact("张2", "18866661002", "18866661002@qq.com"),
                new Contact("张3", "18877771004", ""),
                // Add more contacts here
        };

        // Create a StringBuilder to construct the VCF content
        StringBuilder vcfContent = new StringBuilder();

        // Iterate through the contacts and add their details to the VCF content
        for (Contact contact : contacts) {
            addContact(vcfContent, contact);
        }

        // Specify the file path to save the VCF file
        String filePath = "D:\\lls\\gaojie\\Desktop\\个人打杂\\通讯录相关\\contacts5.vcf";

        try {
            // Create a BufferedWriter to write the VCF content to a file
            BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));
            writer.write(vcfContent.toString());
            writer.close();
            System.out.println("VCF file generated successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将 excel 的内容转换成 vcf
     */
    @Test
    void test02() {

        // 1.读取excel内容，组装vcf文件内容
        String excelPath = "D:\\lls\\gaojie\\Desktop\\个人打杂\\通讯录相关\\通讯录-超人-1.xlsx";
        StringBuilder vcfContent = new StringBuilder();
        EasyExcel.read(excelPath, Contact.class, new PageReadListener<Contact>(dataList -> dataList.forEach(e -> {
            System.out.println(e);
            addContact(vcfContent, e);
        }))).sheet().doRead();

        // 2.输出到vcf文件
        String vcfPath = "D:\\lls\\gaojie\\Desktop\\个人打杂\\通讯录相关\\contacts-20230816-2001.vcf";
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(vcfPath));
            writer.write(vcfContent.toString());
            writer.close();
            System.out.println("Excel 转 Vcf 成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加到vcf内容
     */
    private void addContact(StringBuilder vcfContent, Contact contact) {
        vcfContent.append("BEGIN:VCARD\n");
        vcfContent.append("VERSION:3.0\n");
        vcfContent.append("N:").append(contact.getName()).append("\n");
        vcfContent.append("TEL;TYPE=CELL:").append(contact.getPhone()).append("\n");
        vcfContent.append("EMAIL:").append(contact.getEmail()).append("\n");
        vcfContent.append("END:VCARD\n");
    }
}